package com.didispace;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.codehaus.jettison.json.JSONObject;
import org.codehaus.jettison.json.JSONString;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import rx.Observable;
import rx.Observer;
import rx.Subscriber;

import com.fasterxml.jackson.core.JsonParser;
import com.google.gson.Gson;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.ObservableExecutionMode;
import com.netflix.hystrix.contrib.javanica.command.AsyncResult;


@Service
public class UserService { 

	@Autowired
    RestTemplate restTemplate;
	
	public User syn() {
		User u = new UserCommand(restTemplate, "20").execute();
		return u;
	}
	
	/*
	 * 异步调用
	 */
	public User asyn() throws InterruptedException, ExecutionException {
		Future<User> futureUser = new UserCommand(restTemplate, "30").queue();
		return futureUser.get();
	}
	
	/*
	 * 异步调用
	 */
	@HystrixCommand
	public Future<User> annAsyUser() {
		return new AsyncResult<User>() {
			@Override
			public User invoke() {
				return restTemplate.getForObject("http://eureka-client/users/{1}", User.class, "40");
			}
		};	
	}
	
	public User observe() throws InterruptedException, ExecutionException {
		Gson gson = new Gson();
		Observable<User> observable = new UserCommand(restTemplate, "30").observe();
		List<User> list = new ArrayList<User>();
		observable.subscribe(new Observer<User>() {

			@Override
			public void onCompleted() {
				System.out.println("onCompleted");
				
			}

			@Override
			public void onError(Throwable arg0) {
				System.out.println("onError");
			}

			@Override
			public void onNext(User t) {
				System.out.println(gson.toJson(t));
			}
		});
		
//		observable.subscribe(new Subscriber<User>() {
//
//			@Override
//			public void onCompleted() {
//				// TODO Auto-generated method stub
//				
//			}
//
//			@Override
//			public void onError(Throwable e) {
//				// TODO Auto-generated method stub
//				
//			}
//
//			@Override
//			public void onNext(User t) {
//				// TODO Auto-generated method stub
//				
//			}
//		})
		
		return new User();
	}
	
	public User HystrixObservableObserve() throws InterruptedException, ExecutionException {
		Gson gson = new Gson();
		Observable<User> observable = new UserHystrixObservableCommand(new String[] {"10", "20"}, restTemplate).toObservable();
		observable.subscribe(new Observer<User>() {

			@Override
			public void onCompleted() {
				System.out.println("onCompleted");
				
			}

			@Override
			public void onError(Throwable arg0) {
				System.out.println("onError");
			}

			@Override
			public void onNext(User t) {
				System.out.println(gson.toJson(t));
			}
		});
		
		return new User();
	}
	
}